//
//  QNUtil.m
//  QNReuseTool
//
//  Created by rsh on 2019/10/15.
//  Copyright © 2019年 rsh. All rights reserved.
//

#import "QNUtil.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/PHPhotoLibrary.h>

@implementation QNUtil


#pragma mark - 用户
/**
 截取用户名
 
 @return 用户名
 */
+ (NSString *)interceptUserName:(NSString *)userName{
    NSString *name = [[userName componentsSeparatedByString:@"("]objectAtIndex:0];
    if (name.length >2) {
        NSArray *array = [name componentsSeparatedByString:@"] "];
        if (array.count == 2) {
            name = array[1];
        }
        NSString *match = @"[a-zA-Z]*";
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
        BOOL isEnglish = [predicate evaluateWithObject:name];
        if (isEnglish) {
            return [[name substringWithRange:NSMakeRange(0,2)]uppercaseString];
        }else{
            return [name substringWithRange:NSMakeRange(name.length-2,2)];
        }
    }else{
        return name;
    }
}
#pragma mark - 时间转换
/**
 *  获取当前时间
 *
 *  @param formatString 格式化方式
 *
 *  @return <#return value description#>
 */
+ (NSString *)getCurrentTimeWithFormatString:(NSString *)formatString{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    dateFormat.dateFormat = formatString;
    return [dateFormat stringFromDate:[NSDate date]];
}

/**
 *  获取指定时间的格式化字符串
 *
 *  @param formatString 格式化方式
 *  @param formatDate   格式化时间
 *
 *  @return <#return value description#>
 */
+ (NSString *)getTimeWithFormatString:(NSString *)formatString andFormatDate:(NSDate *)formatDate{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    dateFormat.dateFormat = formatString;
    return [dateFormat stringFromDate:formatDate];
}

/**
 指定格式的时间字符串转date
 
 @param formatString 格式化方式
 @param dateString  时间字符串
 @return <#return value description#>
 */
+ (NSDate *)getDateWithFormatString:(NSString *)formatString andFormatDateString:(NSString *)dateString{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:formatString];
    NSDate *destDate= [dateFormatter dateFromString:dateString];
    return destDate;
}

/**
 将某个时间转化成时间戳
 
 @param formatString 格式化方式
 @param dateString 时间字符串
 @return 时间戳
 */
+ (NSInteger)getTimestampWithFormatString:(NSString *)formatString andDateString:(NSString *)dateString {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:formatString];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate* date = [formatter dateFromString:dateString];
    //时间转时间戳的方法:
    NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue]*1000;
    return timeSp;
}

/**
 将某个时间戳转化成时间
 
 @param timestamp 时间戳
 @param format 格式化方式
 @return 时间
 */
+ (NSString *)getTimeWithTimestamp:(NSString *)timestamp andFormatter:(NSString *)format{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[timestamp longLongValue]/1000];
    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    return confromTimespStr;
}

/**
 判断时间差
 
 @param date1String 时间字符串
 @param date2String 时间字符串
 @return 时间差
 */
+ (NSInteger)differenceWithDate:(NSString *)date1String withDate:(NSString *)date2String{
    
    NSDate *date1 = [QNUtil getDateWithFormatString:@"yyyy-MM-dd HH:mm:ss" andFormatDateString:date1String];
    NSDate *date2 = [QNUtil getDateWithFormatString:@"yyyy-MM-dd " andFormatDateString:date2String];
    NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comps = [gregorian components:NSCalendarUnitDay fromDate:date2 toDate:date1 options:0];
    NSInteger day = [comps day];//时间差
    NSLog(@"时间差 = %ld",(long)day);
    return day;
}

/**
 比较两个日期的大小 日期格式为2016-08-14
 
 @param aDate a日期
 @param bDate b日期
 @return 0：相等；1：b比a大；-1：b比a小
 */
+ (NSInteger)compareDate:(NSString *)aDate withDate:(NSString *)bDate{
    NSInteger aa;
    NSDateFormatter *dateformater = [[NSDateFormatter alloc] init];
    [dateformater setDateFormat:@"yyyy-MM-dd"];
    NSDate *dta = [[NSDate alloc] init];
    NSDate *dtb = [[NSDate alloc] init];
    
    dta = [dateformater dateFromString:aDate];
    dtb = [dateformater dateFromString:bDate];
    NSComparisonResult result = [dta compare:dtb];
    if (result==NSOrderedSame)
    {
        //相等
        aa = 0;
    }else if (result==NSOrderedAscending)
    {
        //bDate比aDate大
        aa = 1;
    }else {
        //bDate比aDate小
        aa = -1;
    }
    
    return aa;
}

/**
 时间差
 
 @param startTime 开始时间
 @param endTime 结束时间
 @return 秒
 */
+ (NSTimeInterval)secondWithStartTime:(NSString *)startTime endTime:(NSString *)endTime{
    
    NSDateFormatter *date = [[NSDateFormatter alloc]init];
    [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *startD = [date dateFromString:startTime];
    NSDate *endD = [date dateFromString:endTime];
    
    NSTimeInterval value = [endD timeIntervalSinceDate:startD];
    
    return value;
}

/**
 获取天时分秒
 
 @param value 秒
 @return 时间
 */
+ (NSString *)getDayHourMinuteSecondWithSecond:(int)value{
    int second = (int)value % 60;//秒
    int minute = (int)value / 60%60;
    int hour = (int)value / 3600%24;
    int day = (int)value / (24*3600);
    NSString *str;
    if (day > 0) {
        str = [NSString stringWithFormat:@"%d天%d时%d分%d秒",day,hour,minute,second];
    }else if (day==0 && hour > 0) {
        str = [NSString stringWithFormat:@"%d时%d分%d秒",hour,minute,second];
    }else if (day==0 && hour==0 && minute>0) {
        str = [NSString stringWithFormat:@"%d分%d秒",minute,second];
    }else if (day==0 && hour==0 && minute==0 && second>0){
        str = [NSString stringWithFormat:@"%d秒",second];
    }
    return str;
}


+ (NSDictionary<NSString *, NSString *> *)getTimeDictWithSecond:(double)value {
    NSInteger day = (NSInteger)value / (24 * 3600);
    NSInteger hour = (NSInteger)value / 3600 % 24;
    NSInteger minute = (NSInteger)value / 60 % 60;
    NSInteger second = (NSInteger)value % 60;
    
    return @{@"day":[NSString stringWithFormat:@"%zd",day],
             @"hour":[NSString stringWithFormat:@"%zd",hour],
             @"minute":[NSString stringWithFormat:@"%zd",minute],
             @"second":[NSString stringWithFormat:@"%zd",second]
             };
}


/**
 获取星期几
 
 @param timeString 时间戳(秒)
 @return 周几
 */
+ (NSString *)weekdayStringFromDate:(NSString *)timeString{
    NSDate *nd = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)([timeString doubleValue]/1000)];
    NSArray *weekdays = [NSArray arrayWithObjects:[NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六",  nil];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Beijing"];
    
    [calendar setTimeZone: timeZone];
    
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:nd];
    
    return [weekdays objectAtIndex:theComponents.weekday];
}


+ (NSString *)dateStrThisWeekFirstDay:(NSString *)first {
    NSArray *weekdays = [NSArray arrayWithObjects:[NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六",  nil];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setTimeZone:[[NSTimeZone alloc] initWithName:@"Asia/Beijing"]];
    
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:[NSDate date]];
    
    return [weekdays objectAtIndex:theComponents.weekday];
}


// 获取当前周的周一和周日的时间
+ (NSString *)dateStrFromSundayToSaturday {
    NSDate *nowDate = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comp = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSDayCalendarUnit fromDate:nowDate];
    // 获取今天是周几
    NSInteger weekDay = [comp weekday];
    // 获取几天是几号
    NSInteger day = [comp day];


    // 计算当前日期和本周的星期一和星期天相差天数
    long firstDiff,lastDiff;
    //    weekDay = 1;
    if (weekDay == 1)
    {
        firstDiff = -6;
        lastDiff = 0;
    }
    else
    {
        firstDiff = [calendar firstWeekday] - weekDay + 1;
        lastDiff = 8 - weekDay;
    }
    NSLog(@"firstDiff: %ld   lastDiff: %ld",firstDiff,lastDiff);

    // 在当前日期(去掉时分秒)基础上加上差的天数
    NSDateComponents *firstDayComp = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit  fromDate:nowDate];
    [firstDayComp setDay:day + firstDiff];
    NSDate *firstDayOfWeek = [calendar dateFromComponents:firstDayComp];

    NSDateComponents *lastDayComp = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit   fromDate:nowDate];
    [lastDayComp setDay:day + lastDiff];
    NSDate *lastDayOfWeek = [calendar dateFromComponents:lastDayComp];

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM月dd日"];
    NSString *firstDay = [formatter stringFromDate:firstDayOfWeek];
    NSString *lastDay = [formatter stringFromDate:lastDayOfWeek];
    NSLog(@"%@=======%@",firstDay,lastDay);

    NSString *dateStr = [NSString stringWithFormat:@"%@-%@",firstDay,lastDay];

    return dateStr;

}


#pragma mark - 校验
/**
 *  判断字符串位為空
 *
 *  @param string 被检查字符串
 *  @param mTrim  是否除去空格和转行符
 *
 *  @return 如果为空,返回YES,否则返回NO
 */
+(BOOL) empytOrNullRemind:(NSString *)string trim:(BOOL)mTrim {
    
    if (string == nil) {
        return YES;
    }
    NSRange rangeOfFirstWantedCharacter = [string rangeOfCharacterFromSet:[[NSCharacterSet whitespaceAndNewlineCharacterSet] invertedSet]];
    if (mTrim && rangeOfFirstWantedCharacter.location == NSNotFound) {
        return YES;
    }
    return NO;
}
/**
 *  校验身份证
 *
 *  @param value 身份证号码
 *
 *  @return 如果正确,返回YES,否则返回NO
 */
+ (BOOL)validateIDCardNumber:(NSString *)value {
    
    value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    NSInteger length =0;
    if (!value) {
        return NO;
    }else {
        length = value.length;
        
        if (length !=15 && length !=18) {
            return NO;
        }
    }
    // 省份代码
    NSArray *areasArray =@[@"11",@"12", @"13",@"14", @"15",@"21", @"22",@"23", @"31",@"32", @"33",@"34", @"35",@"36", @"37",@"41",@"42",@"43", @"44",@"45", @"46",@"50", @"51",@"52", @"53",@"54", @"61",@"62", @"63",@"64", @"65",@"71", @"81",@"82", @"91"];
    
    NSString *valueStart2 = [value substringToIndex:2];
    BOOL areaFlag = NO;
    for (NSString *areaCode in areasArray) {
        if ([areaCode isEqualToString:valueStart2]) {
            areaFlag = YES;
            break;
        }
    }
    
    if (!areaFlag) {
        return false;
    }
    
    
    NSRegularExpression *regularExpression;
    NSUInteger numberofMatch;
    
    int year =0;
    switch (length) {
        case 15:
            year = [value substringWithRange:NSMakeRange(6,2)].intValue +1900;
            
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];//测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:value
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, value.length)];
            
            if(numberofMatch >0) {
                return YES;
            }else {
                return NO;
            }
        case 18:
            
            year = [value substringWithRange:NSMakeRange(6,4)].intValue;
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];//测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:value
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, value.length)];
            
            
            if(numberofMatch >0) {
                int S = ([value substringWithRange:NSMakeRange(0,1)].intValue + [value substringWithRange:NSMakeRange(10,1)].intValue) *7 + ([value substringWithRange:NSMakeRange(1,1)].intValue + [value substringWithRange:NSMakeRange(11,1)].intValue) *9 + ([value substringWithRange:NSMakeRange(2,1)].intValue + [value substringWithRange:NSMakeRange(12,1)].intValue) *10 + ([value substringWithRange:NSMakeRange(3,1)].intValue + [value substringWithRange:NSMakeRange(13,1)].intValue) *5 + ([value substringWithRange:NSMakeRange(4,1)].intValue + [value substringWithRange:NSMakeRange(14,1)].intValue) *8 + ([value substringWithRange:NSMakeRange(5,1)].intValue + [value substringWithRange:NSMakeRange(15,1)].intValue) *4 + ([value substringWithRange:NSMakeRange(6,1)].intValue + [value substringWithRange:NSMakeRange(16,1)].intValue) *2 + [value substringWithRange:NSMakeRange(7,1)].intValue *1 + [value substringWithRange:NSMakeRange(8,1)].intValue *6 + [value substringWithRange:NSMakeRange(9,1)].intValue *3;
                int Y = S %11;
                NSString *M =@"F";
                NSString *JYM =@"10X98765432";
                M = [JYM substringWithRange:NSMakeRange(Y,1)];// 判断校验位
                if ([M isEqualToString:[value substringWithRange:NSMakeRange(17,1)]]) {
                    return YES;// 检测ID的校验位
                }else {
                    return NO;
                }
                
            }else {
                return NO;
            }
        default:
            return false;
    }
}
/**
 *  验证手机号
 *
 *  @param textString 手机号
 *
 *  @return 如果正确,返回YES,否则返回NO
 */
+ (BOOL)validateTelNumber:(NSString *)textString{
    if ([QNUtil empytOrNullRemind:textString trim:YES]) {
        return NO;
    }
    //NSString *number=@"^((1[0-9]))\\d{10}$";
    NSString *number=@"^1[34578]\\d{9}$";
    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",number];
    return [numberPre evaluateWithObject:textString];
}

/**
 *  验证邮箱
 *
 *  @param email 邮箱
 *
 *  @return 如果正确,返回YES,否则返回NO
 */
+ (BOOL)validateEmail:( NSString  *)email{
    if ([QNUtil empytOrNullRemind:email trim:YES]) {
        return NO;
    }
    NSString  *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate  *emailTest = [NSPredicate predicateWithFormat : @"SELF MATCHES%@",emailRegex];
    return  [emailTest  evaluateWithObject:email];
}

/**
 校验字符串只含有数字
 
 @param text text
 @return YES:是 NO:否
 */
+ (BOOL)validateOnlyIntNumber:(NSString *)text {
    BOOL result = NO;
    if (![self empytOrNullRemind:text trim:YES]){
        NSString * regex = @"^[1-9]\\d*|0$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        result = [pred evaluateWithObject:text];
    }
    return result;
}

#pragma mark - 计算label宽高
//size
+ (CGSize)calLabelSize:(UIFont *)fontSize andStr:(NSString *)str withWidth:(CGFloat)widthSize{
    NSDictionary *attribute = @{NSFontAttributeName: fontSize};
    
    CGSize retSize = [str boundingRectWithSize:CGSizeMake(widthSize, 1000)
                                       options:\
                      NSStringDrawingTruncatesLastVisibleLine |
                      NSStringDrawingUsesLineFragmentOrigin |
                      NSStringDrawingUsesFontLeading
                                    attributes:attribute
                                       context:nil].size;
    
    return retSize;
}
//label高
+ (CGFloat)calLabelHeight:(UIFont *)fontSize andStr:(NSString *)str withWidth:(CGFloat)widthSize lineSpacing:(CGFloat)lineSpacing{
    NSMutableParagraphStyle *contentParagraphStyle = [[NSMutableParagraphStyle alloc] init];
    contentParagraphStyle.lineSpacing = lineSpacing;
    NSDictionary *attribute = @{NSFontAttributeName:fontSize};
//                                NSParagraphStyleAttributeName:contentParagraphStyle};
    
    CGSize retSize = [str boundingRectWithSize:CGSizeMake(widthSize, 1000)
                                       options:\
                      NSStringDrawingTruncatesLastVisibleLine |
                      NSStringDrawingUsesLineFragmentOrigin
//                      |NSStringDrawingUsesFontLeading
                                    attributes:attribute
                                       context:nil].size;
    
    return retSize.height;
}

+ (CGFloat)calLabelHeight:(UIFont *)fontSize andStr:(NSString *)str withWidth:(CGFloat)widthSize{
    return [self calLabelHeight:fontSize andStr:str withWidth:widthSize lineSpacing:0];
}

+ (CGFloat)calLabelHeight:(UIFont *)fontSize andStr:(NSString *)str{
    
    
    NSDictionary *attribute = @{NSFontAttributeName: fontSize};
    
    CGSize retSize = [str boundingRectWithSize:CGSizeMake([[UIScreen mainScreen] bounds].size.width- 10, 0)
                                       options:\
                      NSStringDrawingTruncatesLastVisibleLine |
                      NSStringDrawingUsesLineFragmentOrigin |
                      NSStringDrawingUsesFontLeading
                                    attributes:attribute
                                       context:nil].size;
    
    return retSize.height;
    
    
    
}

+ (CGFloat)calLabelHeight:(UIFont *)fontSize andStr:(NSString *)str withWidth:(CGFloat)widthSize WithHeight:(CGFloat)heightSize
{
    NSDictionary *attribute = @{NSFontAttributeName: fontSize};
    
    CGSize retSize = [str boundingRectWithSize:CGSizeMake(widthSize, heightSize)
                                       options:\
                      NSStringDrawingTruncatesLastVisibleLine |
                      NSStringDrawingUsesLineFragmentOrigin |
                      NSStringDrawingUsesFontLeading
                                    attributes:attribute
                                       context:nil].size;
    
    return retSize.height;
}

//label宽度
+ (CGFloat)calLabelWidth:(UIFont *)fontSize andStr:(NSString *)str withHight:(CGFloat)height{
    
    
    NSDictionary *attribute = @{NSFontAttributeName: fontSize};
    
    CGSize retSize = [str boundingRectWithSize:CGSizeMake(1000, height)
                                       options:\
                      NSStringDrawingTruncatesLastVisibleLine |
                      NSStringDrawingUsesLineFragmentOrigin 
//                      NSStringDrawingUsesFontLeading
                                    attributes:attribute
                                       context:nil].size;
    
    return retSize.width;
}


/**
 打电话
 
 @param numStr 电话号码
 */
+ (void)dialWithPhoneNum:(NSString *)numStr {
    NSString *phoneCallStr = [NSString stringWithFormat:@"telprompt://%@", numStr];
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneCallStr] options:@{} completionHandler:nil];
    } else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneCallStr]];
    }
}
/**
 密码正则
 
 @param inputString 电话号码
 */
+ (BOOL)inputShouldLetterOrNum:(NSString *)inputString {
    
    if (inputString.length == 0) return NO;
    
    NSString *regex =@"[a-zA-Z0-9]*";
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    
    return [pred evaluateWithObject:inputString];
}

/**
 校验相机权限
 */
+ (void)checkCameraSuccess:(void (^)(void))success failure:(void (^)(void))failure
{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusDenied || authStatus ==  AVAuthorizationStatusRestricted) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请在设备的设置-隐私-相机中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
        [alert show];
        return;
    }else if (authStatus == AVAuthorizationStatusNotDetermined){
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {//相机权限
            if (granted) {
                if (success) success();
            }else{
                if (failure) failure();
            }
        }];
    }else{
        if (success) success();
    }
}

/**
 校验相册权限
 */
+ (void)checkPhotoSuccess:(void (^)(void))success failure:(void (^)(void))failure
{
    PHAuthorizationStatus authStatus = [PHPhotoLibrary authorizationStatus];
    if (authStatus == PHAuthorizationStatusRestricted || authStatus == PHAuthorizationStatusDenied) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请在设备的设置-隐私-照片中允许访问照片" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
        [alert show];
        return;
    }else if (authStatus == PHAuthorizationStatusNotDetermined){
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized) {
                if (success) success();
            }else {
                if (failure) failure();
            }
        }];
    }else{
        if (success) success();
    }
}


@end
